package com.cls.business.controller;

import com.cls.business.entity.DeclareTopic;
import com.cls.business.entity.Report;
import com.cls.business.service.IDeclareTopicService;
import com.cls.business.service.IReportService;
import com.cls.business.vo.DeclareTopicVO;
import com.cls.common.annotation.ControllerEndpoint;
import com.cls.common.controller.BaseController;
import com.cls.common.entity.MyConstant;
import com.cls.common.entity.QueryRequest;
import com.cls.common.entity.ResponseVO;
import com.cls.common.enums.DictEnum;
import com.cls.common.enums.EmailTextEnum;
import com.cls.common.exception.MyException;
import com.cls.common.utils.EmailSenderUtil;
import com.cls.common.utils.MyUtil;
import com.cls.system.entity.Expert;
import com.cls.system.entity.SysDict;
import com.cls.system.entity.SysFile;
import com.cls.system.entity.User;
import com.cls.system.service.IExpertService;
import com.cls.system.service.ISysDictService;
import com.cls.system.service.ISysFileService;
import com.cls.system.service.IUserService;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 举报表 Controller
 *
 * @author wmm
 * @date 2020-11-23 10:49:10
 */
@Slf4j
@Validated
@Controller
@RequiredArgsConstructor
public class ReportController extends BaseController {

    private final IReportService reportService;

    private final ISysDictService sysDictService;

    private final IExpertService expertService;

    private final IUserService userService;

    private final ISysFileService sysFileService;

    private final EmailSenderUtil emailSenderUtil;

    private final IDeclareTopicService declareTopicService;

    /**
     * 举报表列表页面
     **/
    @GetMapping(MyConstant.VIEW_PREFIX + "biz/report")
    public String reportIndex(Model model) {
        List<SysDict> subjectType = sysDictService.findByParentCode(DictEnum.SUBJECT_TYPE.getCode());
        model.addAttribute("subjectType", subjectType);
        return MyUtil.view("business/report/report");
    }

    /**
     * 专家举报表列表页面
     **/
    @GetMapping(MyConstant.VIEW_PREFIX + "biz/report/expert")
    public String expertCheckList(Model model) {
        List<SysDict> subjectType = sysDictService.findByParentCode(DictEnum.SUBJECT_TYPE.getCode());
        model.addAttribute("subjectType", subjectType);
        return MyUtil.view("business/report/expert/expertReportList");
    }


    /**
     * 举报选取专家页面
     *
     * @return
     */
    @GetMapping(MyConstant.VIEW_PREFIX + "biz/report/distributeExpert/{reportId}")
    public String distributeExpert(@PathVariable Long reportId, Model model) {
        // 学科分类
        List<SysDict> subjectTypeList = sysDictService.findByParentCode(DictEnum.SUBJECT_TYPE.getCode());
        model.addAttribute("subjectTypeList", subjectTypeList);
        model.addAttribute("reportId", reportId);
        return MyUtil.view("business/report/distributeExpert");
    }


    /**
     * 举报表详情页面
     *
     * @return
     */
    @GetMapping(MyConstant.VIEW_PREFIX + "biz/report/reportDetail/{reportId}")
    public String reportDetail(@PathVariable Long reportId, Model model) {
        DeclareTopicVO detail = reportService.findDetail2Report(reportId);
        Long expertId = detail.getReport().getExpertId();
        if (expertId != null) {
            Expert expert = expertService.getById(expertId);
            detail.setExpert(expert);
        } else {
            detail.setExpert(new Expert());
        }
        model.addAttribute("declareTopic", detail);

        Long itemFileId = detail.getReport().getFileId();
        SysFile itemFile;
        if (itemFileId != null) {
            itemFile = Optional.ofNullable(sysFileService.getById(itemFileId)).orElse(new SysFile());
        } else {
            itemFile = new SysFile();
        }
        model.addAttribute("itemFile", itemFile);
        return MyUtil.view("business/report/reportDetail");
    }

    /**
     * 专家显示详情页面
     *
     * @return
     */
    @GetMapping(MyConstant.VIEW_PREFIX + "biz/report/expertCheckDetail/{reportId}")
    public String expertCheckDetail(@PathVariable Long reportId, Model model) {
        DeclareTopicVO detail = reportService.findDetail2Report(reportId);
        Long expertId = detail.getReport().getExpertId();
        if (expertId != null) {
            Expert expert = expertService.getById(expertId);
            detail.setExpert(expert);
        } else {
            detail.setExpert(new Expert());
        }
        model.addAttribute("declareTopic", detail);
        return MyUtil.view("business/report/expert/expertReportDetail");
    }


    @GetMapping("biz/report/list")
    @ResponseBody
    @RequiresPermissions("report:list")
    public ResponseVO reportList(QueryRequest request, DeclareTopic declareTopic) {
       /* //必须查询审核通过的信息方可能展示
        List<String> codes = new ArrayList<>();
        codes.add(DictEnum.ITEM_CHECK_PASSED.getCode());
        codes.add(DictEnum.ITEM_PASSED.getCode());
        declareTopic.setStatusTypeCodes(codes);*/
        PageInfo<DeclareTopicVO> declareTopics = this.reportService.findDeclareTopicsForReport(request, declareTopic);
        return ResponseVO.success(declareTopics);
    }

    @GetMapping("biz/report/expert/list")
    @ResponseBody
//    @RequiresPermissions("expertReport:list")
    public ResponseVO reportExpertList(QueryRequest request, DeclareTopic declareTopic) {
        //必须查询审核通过的信息方可能展示
        List<String> codes = new ArrayList<>();
        codes.add(DictEnum.ITEM_CHECK_PASSED.getCode());
        codes.add(DictEnum.ITEM_PASSED.getCode());
        declareTopic.setStatusTypeCodes(codes);
        //根据用户id获取专家
        Long userId = getCurrentUser().getUserId();
        Expert expert = expertService.findByUserId(userId);
        if (expert != null) {
            declareTopic.setExpertId(expert.getExpertId());
            PageInfo<DeclareTopicVO> declareTopics = this.reportService.findDeclareTopicsForReport(request, declareTopic);
            return ResponseVO.success(declareTopics);
        }else{
            throw new MyException("当前用户不是专家用户！");
        }

    }

    @ControllerEndpoint(operation = "分配专家Report", exceptionMessage = "分配专家Report失败")
    @PostMapping("biz/report/distributeExpert/{reportId}")
    @ResponseBody
    @RequiresPermissions("report:update")
    public ResponseVO updateReport(@PathVariable Long reportId, Long expertId) {
        Report report = new Report();
        report.setReportId(reportId);
        report.setExpertId(expertId);
        reportService.updateById(report);
        //给专家分配账号
        Expert expert = expertService.getById(expertId);
        userService.registerOneExpert(expert);

        //发送邮件

        report = reportService.getById(reportId);
        Long declareId = report.getDeclareId();
        DeclareTopic declareTopic = declareTopicService.getById(declareId);

        String password=null;
        String mobile = expert.getMobile();
        if(mobile != null && mobile.length() > 10) {
            password = mobile.substring(3, 9);
        }
        String message = String.format(EmailTextEnum.REPORT_EXPERT_TEXT.getText(),declareTopic.getName(),mobile,password);
        emailSenderUtil.sendEmail(EmailTextEnum.REPORT_EXPERT.getText(),message,expert.getEmail());
        return ResponseVO.success();
    }

    @ControllerEndpoint(operation = "新增Report", exceptionMessage = "新增Report失败")
    @PostMapping("biz/report")
    @ResponseBody
//    @RequiresPermissions("report:add")
    public ResponseVO addReport(Report report) {
        this.reportService.createReport(report);
        return ResponseVO.success();
    }


    @ControllerEndpoint(operation = "修改Report", exceptionMessage = "修改Report失败")
    @PostMapping("biz/report/update/{reportId}")
    @ResponseBody
//    @RequiresPermissions("report:update")
    public ResponseVO updateReport(@PathVariable Long reportId, Report report) {
        report.setReportId(reportId);
        this.reportService.updateById(report);
        return ResponseVO.success();
    }

}
